<?php

namespace app\models;

use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

/**
 * 代理商
 * Class Agent
 * @package app\models
 *
 * @property integer $id PK
 * @property integer $pid 上级代理商编号
 * @property string $username 登录用户名
 * @property string $password 登录密码
 * @property string $auth_key
 * @property integer $status 状态
 * @property integer $create_time 创建时间
 *
 * @property Agent $parent 关联上级代理商
 */
class Agent extends ActiveRecord implements IdentityInterface
{
    const STATUS_OK = 1;
    const STATUS_STOP = 9;
    const STATUS_DELETE = 0;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password'], 'required'],
            ['username', 'safe'],
            ['company', 'safe'],
            ['tax', 'safe'],
            ['contact', 'safe'],
            ['tel', 'safe'],
            ['express','safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'username' => '用户名',
            'password' => '密码',
            'company'  => '公司名称',
            'tax'      => '税号',
            'contact'  => '联系人',
            'tel'      => '联系电话',
            'express'  => '快递地址'
        ];
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return Agent::findOne(['id' => $id]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return null;
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->auth_key === $authKey;
    }

    /**
     * 生成接口Token
     * @param $appId string 客户端AppId
     * @return string
     */
    public function generateToken($appId)
    {
        $apiClient = ApiClient::findByAppId($appId);
        return Util::makeJWT([
            'iat' => time(),
            'aid' => $this->id,
            'app' => $appId,
        ], $apiClient->app_secret);
    }

    /**
     * 验证密码
     * @param string $password 明文密码
     * @return bool
     */
    public function validatePassword($password)
    {
        return \Yii::$app->security->validatePassword($password, $this->password);
    }

    /**
     * 关联上级代理商
     * @return \yii\db\ActiveQuery
     */
    public function getParent()
    {
        return $this->hasOne(Agent::class, ['id' => 'pid']);
    }

    /**
     * 检查是否有上下级关系
     * @param $parentId integer 上级代理商编号
     * @param $childId integer 下级代理商编号
     * @return bool
     */
    public static function checkRelation($parentId, $childId)
    {
        $agent = Agent::findOne(['id' => $childId]);
        while (!empty($agent->pid)) {
            if ($agent->pid == $parentId) {
                return true;
            }
            $agent = $agent->parent;
        }
        return false;
    }

    /**
     * @inheritdoc
     */
    public function afterSave($insert, $changedAttributes)
    {
        // 创建默认的宣传信息
        if (!AgentPublish::find()->andWhere(['agent_id' => $this->id])->exists()) {
            $publish3 = new AgentPublish();
            $publish3->agent_id = $this->id;
            $publish3->name = '宣传图片';
            $publish3->type = AgentPublish::TYPE_IMAGE;
            $publish3->value = '';
            $publish3->save(false);
            $publish2 = new AgentPublish();
            $publish2->agent_id = $this->id;
            $publish2->name = '联系电话';
            $publish2->type = AgentPublish::TYPE_TEXT;
            $publish2->value = '';
            $publish2->save(false);
            $publish1 = new AgentPublish();
            $publish1->agent_id = $this->id;
            $publish1->name = '服务商';
            $publish1->type = AgentPublish::TYPE_TEXT;
            $publish1->value = '';
            $publish1->save(false);
        }
        parent::afterSave($insert, $changedAttributes);
    }

    /**
     * 返回下级代理商编号列表
     * @param bool $recursion 是否递归返回所有下级
     * @return array
     */
    public function getSubAidList($recursion = true)
    {
        $aidList = [];
        /** @var Agent $agent */
        foreach (Agent::find()->andWhere(['pid' => $this->id])->each() as $agent) {
            $aidList[] = $agent->id;
            if ($recursion) {
                // 递归下一级
                $aidList = array_merge($aidList, $agent->getSubAidList($recursion));
            }
        }
        return $aidList;
    }
}
